package com.atguigu.gmall.realtime.app.dwm;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONAware;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.app.BaseAppV1;
import com.atguigu.gmall.realtime.common.Constant;
import com.atguigu.gmall.realtime.util.AtguiguUtil;
import com.atguigu.gmall.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @Author lzc
 * @Date 2022/4/18 14:02
 */
public class DwmUvApp extends BaseAppV1 {
    public static void main(String[] args) {
        new DwmUvApp().init("DwmUvApp", 3001, 1, "DwmUvApp", "DwmUvApp", Constant.TOPIC_DWD_PAGE);
    }
    
    @Override
    public void handle(StreamExecutionEnvironment env,
                       DataStreamSource<String> stream) {
        stream
            .map(JSON::parseObject)
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((obj, ts) -> obj.getLong("ts"))
            )
            .keyBy(log -> log.getJSONObject("common").getString("mid"))
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .process(new ProcessWindowFunction<JSONObject, JSONObject, String, TimeWindow>() {
    
                private SimpleDateFormat sdf;
                private ValueState<String> dateState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    dateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("dateState", String.class));
    
                    sdf = new SimpleDateFormat("yyyy-MM-dd");
                }
                
                @Override
                public void process(String key,
                                    Context ctx,
                                    Iterable<JSONObject> elements,
                                    Collector<JSONObject> out) throws Exception {
                    // 今天
                    String today = sdf.format(ctx.window().getStart());
                    String yesterday = dateState.value();
    
                    if (!today.equals(yesterday)) {
                        dateState.clear();
                        
                    }
    
                    if (dateState.value() == null) {
                        
                        List<JSONObject> list = AtguiguUtil.toList(elements);
                        //                        Collections.min(list, (o1, o2) -> o1.getLong("ts").compareTo(o2.getLong("ts")))
                        JSONObject min = Collections.min(list, Comparator.comparing(o -> o.getLong("ts")));
    
                        String date = sdf.format(min.getLong("ts"));
                        dateState.update(date);  // 状态中存储年月日
                        
                        out.collect(min);
                    }
                    
                }
            })
            .map(JSONAware::toJSONString)
            .addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWM_UV));
           
    }
}
/*
计算uv: dwm把重复表的记录去重

1. 数据源
    启动日志 ?
        可以, 但是计算的结果不对, 偏少
        打开官方app, 会有启动日志
        如果通过浏览器访问, 没有启动日志
     
     页面日志
        结果比较准确. 不管何种访问方式, 总有第一条访问记录
        
        dwd_page
        
2. 如何去重?  把当天的第一条记录写入到Kafka中


 


 */